<template>
  <div class="chat-container">
    <el-container style="height: 100%;">
      <el-aside width="250px" class="chat-aside">
        <div class="chat-history">
          <h3>历史会话</h3>
          <el-scrollbar>
            <el-menu
              :default-active="activeChat"
              @select="handleSelectChat"
            >
              <el-menu-item 
                v-for="chat in chatHistory" 
                :key="chat.id" 
                :index="chat.id"
              >
                <el-icon><ChatDotRound /></el-icon>
                <span>{{ chat.title }}</span>
              </el-menu-item>
            </el-menu>
          </el-scrollbar>
        </div>
      </el-aside>
      
      <el-container class="chat-main" style="height: 100%;">
        <el-header class="chat-header">
          <div class="chat-title">
            {{ currentChat.title }}
          </div>
          <div class="chat-actions">
            <el-button-group>
              <el-button @click="clearChat" icon="Delete">清空对话</el-button>
              <el-button @click="exportChat" icon="Download">导出对话</el-button>
              <el-button @click="goToUserProfile">用户中心</el-button>
            </el-button-group>
          </div>
        </el-header>

        <div class="new-chat">
          <el-button type="primary" @click="createNewChat" block>
            新建会话
          </el-button>
        </div>
        
        <el-main class="chat-messages" style="height: calc(100% - 150px); overflow-y: auto;">
          <el-scrollbar ref="messageScroller" style="height: 100%;">
            <div v-for="(message, index) in currentChat.messages" 
                 :key="index" 
                 :class="['message', message.type]">
              <el-avatar :size="40" :src="message.avatar || userAvatar" />
              <div class="message-content" :class="{ 'user-message': message.type === 'user' }">
                <div class="message-text" v-html="formatMessage(message.content)"></div>
                <div class="message-timestamp">{{ formatTimestamp(message.timestamp) }}</div>
                <div class="message-actions">
                  <el-button-group>
                    <el-button text size="small" @click="copyMessage(message)">
                      复制
                    </el-button>
                    <el-button text size="small" @click="likeMessage(message)">
                      {{ message.liked ? '已赞' : '点赞' }}
                    </el-button>
                  </el-button-group>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </el-main>

        <el-footer class="chat-footer">
          <el-form @submit.prevent="sendMessage">
            <el-input
              v-model="userInput"
              type="textarea"
              :rows="3"
              placeholder="输入消息，按Ctrl+Enter发送..."
              @keydown.ctrl.enter="sendMessage"
            />
            <div class="input-actions">
              <el-upload
                action="#"
                :auto-upload="false"
                :show-file-list="false"
                @change="handleFileUpload"
              >
                <el-button icon="Paperclip">上传文件</el-button>
              </el-upload>
              <el-button type="primary" @click="sendMessage" :loading="sending">
                发送
              </el-button>
            </div>
          </el-form>
        </el-footer>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import { ChatDotRound } from '@element-plus/icons-vue'
import { marked } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'
import { sendMessageToOllama } from '../api'; // 导入 API 调用函数

export default {
  name: 'ChatBot',
  components: {
    ChatDotRound
  },
  data() {
    return {
      activeChat: '1',
      userInput: '',
      sending: false,
      userAvatar: '', // 用户头像
      chatHistory: [
        {
          id: '1',
          title: '默认对话',
          messages: [
            {
              type: 'bot',
              content: '你好！我是AI助手，很高兴为您服务。',
              avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
              liked: false,
              timestamp: new Date().toLocaleTimeString()
            }
          ]
        }
      ]
    }
  },
  computed: {
    currentChat() {
      return this.chatHistory.find(chat => chat.id === this.activeChat) || this.chatHistory[0]
    }
  },
  methods: {
    formatMessage(content) {
      return marked(content, {
        highlight: function(code, lang) {
          if (lang && hljs.getLanguage(lang)) {
            return hljs.highlight(code, { language: lang }).value
          }
          return hljs.highlightAuto(code).value
        }
      })
    },
    formatTimestamp(timestamp) {
      return new Date(timestamp).toLocaleTimeString(); // 格式化时间戳
    },
    async sendMessage() {
      if (!this.userInput.trim()) return
      
      const message = {
        type: 'user',
        content: this.userInput,
        avatar: this.userAvatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png', // 使用用户头像
        liked: false,
        timestamp: new Date() // 添加时间戳
      }
      
      this.currentChat.messages.push(message)
      this.userInput = ''
      this.sending = true
      
      // 调用 Ollama API
      try {
        const reply = await sendMessageToOllama(this.userInput); // 使用封装的 API 调用
        const botMessage = {
          type: 'bot',
          content: reply, // 使用 API 返回的回复
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
          liked: false,
          timestamp: new Date() // 添加时间戳
        };
        
        this.currentChat.messages.push(botMessage);
      } catch (error) {
        console.error('API 调用失败:', error);
        this.$message.error('发送消息失败，请稍后再试。');
      } finally {
        this.sending = false;
        this.scrollToBottom();
      }
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const scrollbar = this.$refs.messageScroller
        scrollbar.setScrollTop(scrollbar.wrapRef.scrollHeight)
      })
    },
    createNewChat() {
      const newChat = {
        id: Date.now().toString(),
        title: `新对话 ${this.chatHistory.length + 1}`,
        messages: []
      }
      this.chatHistory.push(newChat)
      this.activeChat = newChat.id
    },
    handleSelectChat(id) {
      this.activeChat = id
    },
    clearChat() {
      this.$confirm('确认清空当前对话？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.currentChat.messages = []
      })
    },
    exportChat() {
      const content = this.currentChat.messages
        .map(m => `${m.type}: ${m.content}`)
        .join('\n\n')
      
      const blob = new Blob([content], { type: 'text/plain' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `chat-${this.currentChat.id}.txt`
      a.click()
      URL.revokeObjectURL(url)
    },
    copyMessage(message) {
      navigator.clipboard.writeText(message.content)
      this.$message.success('已复制到剪贴板')
    },
    likeMessage(message) {
      message.liked = !message.liked
    },
    handleFileUpload(file) {
      // 处理文件上传
      console.log('上传文件:', file)
    },
    goToUserProfile() {
      this.$router.push('/user-profile'); // 跳转到用户中心
    }
  }
}
</script>

<style scoped>
.chat-container {
  height: calc(100vh - 64px);
}

.chat-aside {
  background: #f5f7fa;
  border-right: 1px solid #e6e6e6;
  display: flex;
  flex-direction: column;
}

.chat-history {
  flex: 1;
  overflow: hidden;
}

.chat-history h3 {
  padding: 20px;
  margin: 0;
}

.new-chat {
  padding: 20px;
}

.chat-main {
  background: #fff;
}

.chat-header {
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
}

.chat-messages {
  padding: 20px;
  overflow-y: auto; /* 允许垂直滚动 */
}

.message {
  display: flex;
  margin-bottom: 20px;
  gap: 12px;
}

.message-content {
  flex: 1;
  background: #f5f7fa;
  padding: 12px;
  border-radius: 8px;
}

.user-message {
  align-self: flex-end; /* 用户消息右对齐 */
  background-color: white;
}

.bot .message-content {
  background: #ecf5ff;
}

.message-timestamp {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.message-actions {
  margin-top: 8px;
  text-align: right;
}

.chat-footer {
  border-top: 1px solid #e6e6e6;
  padding: 20px;
  height: 200px;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 12px;
}

:deep(.markdown-body) {
  background: transparent !important;
}

:deep(pre) {
  background: #f8f9fa !important;
  padding: 16px !important;
  border-radius: 4px !important;
}
</style> 